<template>
  <div>
    <div class="map_shuj">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="巡检路线">
          <el-select v-model="ruleForm.patrolRouteType" placeholder="请选择巡检路线">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 签到点 -->
      <div class="map_qiandao_dain">
        <span>签到点：</span>
        <el-tag :key="i" v-for="(tag, i) in dynamicTags" closable :disable-transitions="false" @close="handleClose(i)">
          签到点:{{  i + 1  }}
        </el-tag>
        <el-button class="button-new-tag" size="small" @click="button1">+添加签到点</el-button>
        输入地址
        <!-- <el-input
          v-model="autoOptions"
          size="mini"
          style="width: 100px"
        ></el-input> -->
        <el-autocomplete v-model="mapsearch" :fetch-suggestions="querySearchAsync" :trigger-on-focus="false"
          @input="searchlat" @select="handleSelectScenic" placeholder="请选择地址"></el-autocomplete>
        <!-- <el-button size="small" @click="searchAddress()">搜索</el-button> -->
      </div>
      <div class="map_qiandao_dain_xia">
        <el-button v-show="ruleForm.patrolRouteType === 20" size="small" @click="drawPolyline()">添加线路</el-button>
        <el-button v-show="ruleForm.patrolRouteType === 30" size="small" @click="drawPolygon()">添加区域</el-button>
      </div>
      <div class="map_shuj_button">
        <el-button type="primary" @click="submitForm('ruleForm')">保 存</el-button>
        <el-button @click="resetForm('ruleForm')">重 置</el-button>
      </div>
    </div>
    <div class="map_box_xia">
      <div id="map_box" class="map_box"></div>
      <!-- <el-dialog
  title="签到点详情"
  :visible.sync="dialogVisible"
  width="30%"
  > -->
      <div class="map_box_you" v-show="this.inglatxy1">
        <div class="map_box_you_top"><span>签到点详情</span></div>
        <div class="map_box_you_xia">
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="类型">
              <el-select v-model="form.region" placeholder="请选择类型">
                <el-option label="普通" value="1"></el-option>
                <el-option label="高危" value="2"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="序号">
              <el-input v-model="form.number"></el-input>
            </el-form-item>
            <el-form-item label="当前所选地址">
              <el-input type="textarea" v-model="form.address"></el-input>
            </el-form-item>
            <el-form-item label="经纬度">
              <el-input v-model="form.latitude"></el-input>
            </el-form-item>
            <el-form-item label="巡检要求">
              <el-input type="textarea" v-model="form.requirement"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit">确 定</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="onSubmit(),dialogVisible = false">确 定</el-button>
  </span> -->
      <!-- </el-dialog> -->

    </div>
  </div>
</template>

<script>
export default {
  name: "FlSmartWaterCloudPlatformFrontXianluditu",
  props: ["selected",'qiandaodianshuju'],
  data() {
    return {
      ccc:'',
      //签到点详情
      form: {
        region: "1",
        number: 1,
        address: "",
        latitude: "",
        requirement: "",
      },
      dialogVisible: false,
      // 签到
      dynamicTags: [],
      inputVisible: false,
      inputValue: "",
      // 选择
      ruleForm: {
        patrolRouteType: 10,
      },
      options: [
        {
          value: 10,
          label: "定点巡检",
        },
        {
          value: 20,
          label: "沿线巡检",
        },
        {
          value: 30,
          label: "区域巡检",
        },
      ],
      // 必填
      rules: {
        patrolRouteType: [
          { required: true, message: "请选择巡检路线", trigger: "change" },
        ],
      },
      inputs: "", //经纬度
      buton: "",
      // autoOptions: "",

      jinduwweidu: null,
      geocoder: null,
      lnglatXY: "", //路线的
      inglatxy1: "", //点位的
      inglatxy2: [], //范围的
      mouseTool: null,
      polyline: null,
      polygon: null,
      map: null,
      marker:null,
      pathpolyline: [],
      getLng: "",
      getLat: "",
      points: [],
      PatrolPlanAddReq: {},
      mapsearch: '',
      maplist: '',
      markerList:[],
    };
  },

  mounted() {
    this.init();
    console.log(this.qiandaodianshuju,'666666666666666666666');
    this.dynamicTags=this.qiandaodianshuju.map(item=>{
      let ttt=[]
      ttt=[item.latitude,item.longitude]
      return ttt
    })
    this.points=this.qiandaodianshuju.map(i=>{
      let ss={
        latitude:i.latitude,
        longitude:i.longitude,
        patrolRequest:i.patrolRequest,
        pointRiskType:i.pointRiskType,
        signAddress:i.signAddress
      }
     return ss
  })
  
  console.log(this.points,'777777777777777777777');
    this.map.remove(this.markerList); // 删除所有点位
    
  // positionList.splice(1, 1);

  for (var i = 0; i < this.dynamicTags.length; i++) {
     let index = i+1 // 序号
    var content = '<div class="marker-icon"><div> '+ index +'</div> </div>';; // 自定义marker

    this.marker = new AMap.Marker({
      content: content,
      position: this.dynamicTags[i]
    });
    this.map.add(this.marker);

    this.markerList.push(this.marker);
  }

  var zhenzhdatas = {
        points: this.points,
        patrolRouteType: this.ruleForm.patrolRouteType,
        routePoints: this.qiandaodianshuju.routePoints,
        // patrolBy: "haibin"
      };
      console.log(zhenzhdatas,'sdadasdasdddddddddddddd');
      this.PatrolPlanAddReq = zhenzhdatas;
  },

  methods: {
    setcenter(lng, lat) {
      this.map.setCenter([lng, lat]);
    },
    querySearchAsync(queryString, cd) {
      let arr = [];
      this.maplist.forEach((item) => {
        let obj = {
          value: item.address + item.name,
          la: item.location.lng + "," + item.location.lat,
          id: item.id,
          lat: item.location.lat,
          lng: item.location.lng,
        };
        arr.push(obj);
      });
      console.log(arr);
      this.timeout = setTimeout(() => {
        console.log(this.maplist);
        // 调用组件自定方法展示搜索结果
        cd(arr);
      }, 2000 * Math.random());
    },

    handleSelectScenic(item) {
      // item是点击选中的一项
      console.log("item==>", item);
      [this.lng, this.lat, this.address, this.mapAddress, this.location] = [
        item.lng,
        item.lat,
        item.value,
        item.value,
        item.la,
      ];

      this.setcenter(this.lng, this.lat);
      this.maplist.forEach((item) => {
        console.log(item);
        // this.addmarker(item.location.lng, item.location.lat);
      });
      this.map.zoom = 8;
    },
    // 地图初始化函数，本例取名为init，开发者可根据实际情况定义
    searchlat() {
      console.log("我执行了");
      this.map.plugin("AMap.PlaceSearch", () => {
        let PlaceSearchOptions = {
          //设置PlaceSearch属性
          city: "全国", //城市
          type: "", //数据类别
          pageSize: 10, //每页结果数,默认10
          pageIndex: 1, //请求页码，默认1
          extensions: "base", //返回信息详略，默认为base（基本信息）
        };
        var MSearch = new AMap.PlaceSearch(PlaceSearchOptions); //构造PlaceSearch类
        console.log(AMap, "amap");
        AMap.Event.addListener(MSearch, "complete", (res) => {
          console.log(res, "我是地图返回值");
          this.maplist = res.poiList.pois;
          console.log(this.maplist);
        }); //返回结果
        MSearch.search(this.mapsearch); //关键字查询
      });
    },
    // 地图
    init() {
      var that = this;
      that.map = new AMap.Map("map_box", {
        rotateEnable: true,
        resizeEnable: true,
        pitchEnable: true,
        zoom: 14,
        pitch: 75,
        rotation: -15,
        // center: [114.128624, 22.663314],
        terrain: true,
      });

      that.geocoder = new AMap.Geocoder({
        radius: 1000,
        // extensions: "all",
      });

      that.marker = new AMap.Marker();
      that.map.on("click", (e) => {
        // regeocoder(lnglatXY);
        if (this.buton === "yanxian") {
          this.lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
          this.pathpolyline.push(this.lnglatXY);
          that.polyline = new AMap.Polyline({
            path: that.pathpolyline,
            isOutline: true,
            outlineColor: "#ffeeff",
            borderWeight: 3,
            strokeColor: "#3366FF",
            strokeOpacity: 1,
            strokeWeight: 6,
            // 折线样式还支持 'dashed'
            strokeStyle: "solid",
            // strokeStyle是dashed时有效
            strokeDasharray: [10, 5],
            lineJoin: "round",
            lineCap: "round",
            zIndex: 50,
          });
          that.polyline.setMap(that.map);
          new AMap.PolyEditor(that.map, that.polyline);
        } else if (this.buton === "fanwei") {
          this.lnglatXY = [e.lnglat.getLng(), e.lnglat.getLat()];
          this.inglatxy2.push(this.lnglatXY);
          that.polygon = new AMap.Polygon({
            path: that.inglatxy2,
            strokeColor: "#FF33FF",
            strokeWeight: 6,
            strokeOpacity: 0.2,
            fillOpacity: 0.4,
            fillColor: "#1791fc",
            zIndex: 50,
          });
          that.map.add(that.polygon);
          // 缩放地图到合适的视野级别
          new AMap.PolyEditor(that.map, that.polygon);
        } else if (this.buton === "dianwei") {
          this.inglatxy1 = [e.lnglat.getLng(), e.lnglat.getLat()];
          (this.getLng = e.lnglat.getLng()),
            (this.getLat = e.lnglat.getLat()),
            (this.inputs = [e.lnglat.getLng() + "," + e.lnglat.getLat()]);
          this.form.latitude = this.inputs[0];
          this.regeoCode();
          this.AddPoint(this.inglatxy1)
          this.form.number = this.dynamicTags.length+1
          // var content = '<div class="marker-icon"><div> '+ 6 +'</div> </div>'; // 自定义marker
          // new AMap.Marker({
          //   content: content,
          //   position: this.inglatxy1,
          //   map: that.map,
          // });
          

        }
      });
    },
    AddPoint (arr) {
  let index = 1 + this.dynamicTags.length // 序号
  var content = '<div class="marker-icon"><div> '+ index +'</div> </div>'; // 自定义marker

  this.marker = new AMap.Marker({
    content: content,
    position: arr,//位置
  })

  this.markerList.push(this.marker)

  this.map.add(this.marker);//添加到地图
},
    //绘制线段
    drawPolyline() {
      this.buton = "yanxian";
    },
    //绘制区域
    drawPolygon() {
      this.buton = "fanwei";
    },
    //地理位置根据经纬度得到地址
    regeoCode() {
      var that = this;
      // console.log(that.inglatxy1);
      that.geocoder.getAddress(that.inglatxy1, function (status, result) {
        if (status === "complete" && result.regeocode) {
          var address = result.regeocode.formattedAddress;
          that.form.address = address;
        } else {
          log.error("根据经纬度查询地址失败");
        }
      });
    },
    button1() {
      this.buton = "dianwei";
    },
    // 删除签到点
    handleClose(tag) {
      console.log(tag,'1111111111111');
      // this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      this.dynamicTags.splice(tag, 1);

      this.map.remove(this.markerList); // 删除所有点位

  // positionList.splice(1, 1);

  for (var i = 0; i < this.dynamicTags.length; i++) {
     let index = i+1 // 序号
    var content = '<div class="marker-icon"><div> '+ index +'</div> </div>';; // 自定义marker

    this.marker = new AMap.Marker({
      content: content,
      position: this.dynamicTags[i]
    });
    this.map.add(this.marker);

    this.markerList.push(this.marker);
  }
    },
    // 确定
    onSubmit() {
      // this.form.number = this.dynamicTags.length + 2
      var qindaoxingxi = {
        latitude: this.getLng,
        longitude: this.getLat,
        patrolRequest: this.form.requirement,
        pointRiskType: this.form.region,
        signAddress: this.form.address,
      };
      
      var arr = this.pathpolyline;
      var arr1 = this.inglatxy2;
      var str = arr.join("-");
      var str1 = arr1.join("-");
      this.points.push(qindaoxingxi);
      console.log(this.points,'2222222222');
      var zhenzhdata = {
        points: this.points,
        patrolRouteType: this.ruleForm.patrolRouteType,
        routePoints: this.pathpolyline.length ? str : str1,
        // patrolBy: "haibin"
      };
      console.log(zhenzhdata.routePoints);
      this.PatrolPlanAddReq = zhenzhdata;
      // console.log(this.points);
      if (this.inglatxy1) {

        this.dynamicTags.push(this.inglatxy1);
        console.log(this.dynamicTags);
        // AddPoint(this.dynamicTags)
        this.inglatxy1 = "";
      }
    },
    showInput() {
      this.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // ba提交数据
    submitForm(formName) {
      var sss=new Array();
      this.PatrolPlanAddReq.points.map(item=>{
        this.dynamicTags.map(i=>{
          if(item.latitude==i[0]){
            sss.push(item)
          }
        })
        
      })
      this.PatrolPlanAddReq.points=sss
      console.log(sss,'3333333');
      this.$emit("update:selected", false);
      this.$emit("chualaide", this.PatrolPlanAddReq);
      this.pathpolyline = []; //沿线线路
      this.inglatxy2 = []; //范围
      this.dynamicTags = []; //签到点1，2，3
      this.points = [];
      this.mapsearch = '';
      this.$refs[formName].validate((valid) => {
        if (valid) {
          console.log(valid);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //重置
    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.map.clearMap();
      this.pathpolyline = []; //沿线线路
      this.inglatxy2 = []; //范围
      this.dynamicTags = []; //签到点1，2，3
      this.inglatxy1 = ""; //点位
      this.points = []; //整体数据
      this.form.number = 1
      this.mapsearch = '';
    },
  },
};
</script>

<style lang="scss" scoped>
.map_box_xia {
  width: 100%;
  display: flex;
  margin-top: 50px;
  height: 600px;

  #map_box {
    margin: 0;
    padding: 0;
    // flex: 0 0 70%;
    width: 100%;
    height: 500px;

    /deep/.marker-icon {
    width: 40px;
    height: 40px;
    background-image: url(../../../../img/others.png);
    padding-right: 20px;
background-size:100% 100%;
    background-repeat: no-repeat;
    div{
      font-size: 14px;
      color: rgb(255, 0, 0);
      font-weight: 600;
      padding: 6px 0 0 16px;
    }
    }
  }

  .map_box_you {
    flex: 0 0 30%;

    // border: 1px solid rgb(122, 122, 122);
    // width: 00px;
    .map_box_you_top {
      height: 50px;
      // color: rgb(13, 150, 248);
      background-color: rgb(13, 150, 248);
      align-content: center;
      width: 100%;
      padding-left: 8px;

      span {
        line-height: 50px;
        font-size: 16px;
        color: #fff;
        font-weight: 600;
      }
    }

    .map_box_you_xia {
      margin-top: 10px;
    }
  }
}

.map_shuj {
  width: 100%;
  height: 80px;

  .map_qiandao_dain_xia {
    margin-top: 5px;
    margin-bottom: 8px;

    /deep/.el-button--small,
    .el-button--small.is-round {
      padding: 7px 15px;
    }

    /deep/.el-button+.el-button {
      margin-left: 0;
    }
  }
}

.map_shuj_button {
  position: absolute;
  bottom: 4%;
  right: 5%;
}

.el-tag+.el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>